package com.app.model 
{
	import flash.events.Event;
	import flash.net.URLRequest;
	import flash.net.URLLoader;
	import flash.net.URLVariables;
	import flash.net.URLRequestMethod;
	import flash.events.IOErrorEvent;
	import flash.external.ExternalInterface;
	
	import com.adobe.serialization.json.JSON;
	
	import org.puremvc.as3.patterns.proxy.Proxy;
	import org.puremvc.as3.interfaces.IProxy;
	
	import com.peachcastle.debug.Log;
	
	/**
	 * ...
	 * @author kevin
	 */
	public class HttpProxy extends Proxy implements IProxy
	{
		public static const NAME:String = 'HttpProxy';
		
		public static const FEEDBACK_SEND_INFO:String = NAME + "_FeedbackSendInfo";
		public static const FEEDBACK_SEND_AFFIX:String = NAME + "_FeedbackSendAffix";
		
		private var _apiUrl:String = "";
		private var _feedbackUrl:String = "";
		
		public function HttpProxy() 
		{
			super(NAME);
		}
		
		public function init(apiUrl:String = '', feedbackUrl:String = ''):void
		{
			_apiUrl = apiUrl;
			_feedbackUrl = feedbackUrl;
		}
		
		public function sendData(cmd:String, data:Object = null):void
		{
			var callback:Function = null;
			if (data.hasOwnProperty('callback'))
			{
				callback = data['callback'];
				delete data['callback'];
			}
			
			switch(cmd)
			{
				case HttpProxy.FEEDBACK_SEND_INFO:
					sendFeedbak(data, callback, "ctl=fbk_feedback&act=receiveInfo");
					
					break;
					
				case HttpProxy.FEEDBACK_SEND_AFFIX:
					sendFeedbak(data, callback, "ctl=fbk_feedback&act=receiveAffix");
					
					break;
			}
		}
		
		private function sendFeedbak(data:Object = null, callback:Function = null, address:String = ''):void
		{
			var value:URLVariables = new URLVariables();
			value.api = JSON.encode(data);
			var _request:URLRequest = new URLRequest();
			_request.method = URLRequestMethod.POST;
			_request.data = value;
			_request.url = _feedbackUrl + "?" + address;
			connect(callback, _request);
			
			_request = null;
		}
		
		/**
		 * 
		 * @param	callback 回调方法
		 * @param	_request 请求数据;
		 * @param	param 用来过调，防止异步;
		 */
		private function connect(callback:Function = null, _request:URLRequest = null, param:Object = null):void
		{
			if (!ExternalInterface.available) return;
			
			var _loader:URLLoader = new URLLoader();
			_loader.addEventListener(Event.COMPLETE, onComplete);
			try
			{
				_loader.load(_request);
			}catch (err:IOErrorEvent)
			{
				
			}
			
			function onComplete(event:Event):void
			{
				_loader.removeEventListener(Event.COMPLETE, onComplete);

				var obj:Object = JSON.decode(_loader.data) as Object;
				
				Log.debug("HttpProxy onComplete...", _loader.data, obj, callback);
				
				if (param)
				{
					callback(obj, param);
				}else
				{
					callback(obj);
				}
				
				_loader = null;
			}			
		}		
	}

}